package main

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// User 拥有并属于多种 language，`user_languages` 是连接表
type User struct {
	gorm.Model
	Languages []Language `gorm:"many2many:user_languages;"`
}

type Language struct {
	gorm.Model
	Name string
}

func main() {
	dsn := "root:root@tcp(192.168.4.111:3306)/mytest?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		fmt.Println("err", err)
	}

	// _ = db.AutoMigrate(&User{})
	// 创建数据
	/**
	lans := []Language{
		{
			Name: "go",
		},
		{
			Name: "swift",
		},
		{
			Name: "javascript",
		},
	}
	user := User{
		Languages: lans,
	}

	db.Create(&user)
	*/

	// 获取数据
	// 1.preload
	/**
	var user User
	res := db.Preload("Languages").First(&user)
	fmt.Println("user", user)
	fmt.Println("res.Error", res.Error)
	fmt.Println("res.RowsAffected", res.RowsAffected)
	fmt.Println("<<==============================>>")
	*/

	// 2.已经取出了用户, 但是没有使用preload来加载对应的Languages
	// 开始关联模式, 查找关联
	var user User
	languages := []Language{}
	db.First(&user)
	db.Model(&user).Association("Languages").Find(&languages)
	fmt.Println("user", user)
	fmt.Println("Language", languages)
}
